<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="订单号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable>
            <el-option v-for="(item, index) in orderStatusOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="orderList"
      border
      style="width: 100%"
    >
      <el-table-column prop="orderId" label="订单ID" width="80" align="center" />
      <el-table-column prop="goodsId" label="商品ID" width="80" align="center" />
      <el-table-column prop="orderUser" label="用户ID" width="80" align="center" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="orderNum" label="数量" width="80" align="center" />
      <el-table-column prop="orderStatus" label="订单状态" width="120" align="center">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.orderStatus)">
            {{ getOrderStatusText(scope.row.orderStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="180" />
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleDetail(scope.row)">详情</el-button>
          <el-button 
            v-if="scope.row.orderStatus === 1" 
            type="primary" 
            size="small" 
            @click="handleUpdateStatus(scope.row, 2)"
          >发货</el-button>
          <el-button 
            v-if="scope.row.orderStatus === 2" 
            type="success" 
            size="small" 
            @click="handleUpdateStatus(scope.row, 3)"
          >确认收货</el-button>
          <el-button 
            v-if="scope.row.orderStatus === 0" 
            type="danger" 
            size="small" 
            @click="handleUpdateStatus(scope.row, 5)"
          >取消订单</el-button>
          <el-button 
            v-if="scope.row.orderStatus === 6" 
            type="warning" 
            size="small" 
            @click="handleUpdateStatus(scope.row, 7)"
          >同意退单</el-button>
          <el-button 
            v-if="scope.row.orderStatus === 6" 
            type="danger" 
            size="small" 
            @click="handleUpdateStatus(scope.row, 8)"
          >拒绝退单</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="dialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单ID">{{ detailForm.orderId }}</el-descriptions-item>
        <el-descriptions-item label="商品ID">{{ detailForm.goodsId }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ detailForm.orderUser }}</el-descriptions-item>
        <el-descriptions-item label="单价">¥{{ detailForm.price }}</el-descriptions-item>
        <el-descriptions-item label="数量">{{ detailForm.orderNum }}</el-descriptions-item>
        <el-descriptions-item label="总价">¥{{ detailForm.price * detailForm.orderNum }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(detailForm.orderStatus)">
            {{ getOrderStatusText(detailForm.orderStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item v-if="detailForm.reason" label="取消原因">{{ detailForm.reason }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderPage, getOrderDetail, saveOrUpdateOrder } from '@/api/order'

// 订单列表
const orderList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)
// 表单对话框可见状态
const dialogVisible = ref(false)
// 详情表单数据
const detailForm = reactive({
  orderId: null,
  goodsId: null,
  orderUser: null,
  price: 0,
  orderNum: 0,
  orderStatus: 0,
  createTime: '',
  reason: null
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  orderNo: '',
  orderStatus: null
})

// 订单状态选项
const orderStatusOptions = [
  { label: '下单', value: 0 },
  { label: '已付款', value: 1 },
  { label: '已发货', value: 2 },
  { label: '已收货', value: 3 },
  { label: '已评价', value: 4 },
  { label: '已取消', value: 5 },
  { label: '退单中', value: 6 },
  { label: '已退单', value: 7 },
  { label: '拒绝退单', value: 8 }
]

// 获取订单状态文本
const getOrderStatusText = (status) => {
  const found = orderStatusOptions.find(item => item.value === status)
  return found ? found.label : '未知状态'
}

// 获取订单状态标签类型
const getOrderStatusType = (status) => {
  switch (status) {
    case 0:
      return 'info'     // 下单
    case 1:
      return 'warning'  // 已付款
    case 2:
      return 'primary'  // 已发货
    case 3:
      return 'success'  // 已收货
    case 4:
      return 'success'  // 已评价
    case 5:
      return 'danger'   // 已取消
    case 6:
      return 'warning'  // 退单中
    case 7:
      return 'info'     // 已退单
    case 8:
      return 'danger'   // 拒绝退单
    default:
      return 'info'
  }
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取订单列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getOrderPage(queryParams)
    orderList.value = res.data.list || []
    total.value = res.data.total || 0
    console.log('获取到订单数据:', orderList.value)
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.orderNo = ''
  queryParams.orderStatus = null
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理订单详情
const handleDetail = async (row) => {
  try {
    // 如果后端提供了获取详情的单独接口
    // const res = await getOrderDetail(row.orderId)
    // Object.assign(detailForm, res.data)
    
    // 如果没有单独的详情接口，直接使用表格中的行数据
    Object.assign(detailForm, row)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取订单详情失败:', error)
  }
}

// 处理更新订单状态
const handleUpdateStatus = (row, status) => {
  const statusText = getOrderStatusText(status)
  ElMessageBox.confirm(
    `确认将订单 #${row.orderId} 状态修改为"${statusText}"吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const updateData = { ...row, orderStatus: status }
      await saveOrUpdateOrder(updateData)
      ElMessage({
        type: 'success',
        message: '订单状态更新成功!'
      })
      await fetchData()
    } catch (error) {
      console.error('更新订单状态失败:', error)
    }
  }).catch(() => {
    // 取消操作
  })
}
</script> 